<template>
  <div class="address-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>地址管理</span>
          <el-button type="primary" @click="handleAdd">新增地址</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <address-search
        ref="searchFormRef"
        @search="handleSearch"
        @reset="handleReset"
      />

      <!-- 地址列表表格 -->
      <el-table 
        :data="addressList" 
        style="width: 100%" 
        v-loading="loading"
        empty-text="暂无数据"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="contact" label="联系人" width="120" />
        <el-table-column prop="mobile" label="手机号" width="120" />
        <el-table-column label="所在地区" min-width="200">
          <template #default="scope">
            {{ getRegionNames(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="street" label="详细地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="notes" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="isDefault" label="是否默认" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isDefault === 1 ? 'success' : 'info'">
              {{ scope.row.isDefault === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              link
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button 
              type="danger" 
              link
              @click="handleDelete(scope.row.id)"
            >删除</el-button>
            <el-button 
              v-if="scope.row.isDefault !== 1"
              type="success" 
              link
              @click="handleSetDefault(scope.row.id)"
            >设置默认</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          :total="total"
          :page-count="Math.ceil(total / queryParams.pageSize)"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 地址详情对话框 -->
    <el-dialog 
      title="地址详情" 
      v-model="dialogVisible"
      width="500px"
    >
      <div class="address-detail-dialog" v-if="currentAddress">
        <div class="detail-item">
          <label>用户ID：</label>
          <span>{{ currentAddress.userId }}</span>
        </div>
        <div class="detail-item">
          <label>联系人：</label>
          <span>{{ currentAddress.contact }}</span>
        </div>
        <div class="detail-item">
          <label>手机号码：</label>
          <span>{{ currentAddress.mobile }}</span>
        </div>
        <div class="detail-item">
          <label>所在地区：</label>
          <span>{{ getRegionNames(currentAddress) }}</span>
        </div>
        <div class="detail-item">
          <label>详细地址：</label>
          <span>{{ currentAddress.street }}</span>
        </div>
        <div class="detail-item" v-if="currentAddress.notes">
          <label>备注：</label>
          <span>{{ currentAddress.notes }}</span>
        </div>
        <div class="detail-item">
          <label>是否默认：</label>
          <span>{{ currentAddress.isDefault === 1 ? '是' : '否' }}</span>
        </div>
      </div>
    </el-dialog>

    <!-- 地址表单对话框 -->
    <address-form
      v-model:visible="formDialogVisible"
      :title="formTitle"
      :address-data="currentAddress"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { AddressDTO } from '@/api/address'
import { getAddressList, deleteAddress, setDefaultAddress } from '@/api/address'
import AddressForm from './components/AddressForm.vue'
import AddressSearch from './components/AddressSearch.vue'
import { getAreaName } from '@/utils/areaData'

interface RegionOption {
  value: string
  label: string
  children?: RegionOption[]
}

const addressList = ref<AddressDTO[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const formDialogVisible = ref(false)
const formTitle = ref('新增地址')
const currentAddress = ref<AddressDTO>()
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userId: undefined,
  province: '',
  city: '',
  town: '',
  street: '',
  contact: '',
  mobile: '',
  isDefault: undefined
})

// 查询按钮点击
const searchFormRef = ref()
const handleSearch = (params: any) => {
  queryParams.userId = params.userId
  queryParams.province = params.province
  queryParams.city = params.city
  queryParams.town = params.town
  queryParams.contact = params.contact
  queryParams.mobile = params.mobile
  queryParams.isDefault = params.isDefault
  queryParams.pageNum = 1
  fetchAddressList()
}

// 重置查询
const handleReset = () => {
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.userId = undefined
  queryParams.province = ''
  queryParams.city = ''
  queryParams.town = ''
  queryParams.contact = ''
  queryParams.mobile = ''
  queryParams.isDefault = undefined
  fetchAddressList()
}

// 获取地址列表
const fetchAddressList = async () => {
  loading.value = true
  try {
    const res = await getAddressList(queryParams)
    console.log('API Response:', res)
    
    // 使用类型断言处理响应数据
    const responseData = res as any
    
    // 确保数据存在且格式正确
    if (responseData?.data?.data?.list) {
      addressList.value = responseData.data.data.list
      total.value = parseInt(responseData.data.data.total) || 0
    } else if (responseData?.data?.list) {
      // 兼容不同的响应格式
      addressList.value = responseData.data.list
      total.value = parseInt(responseData.data.total) || 0
    } else {
      addressList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('Error fetching address list:', error)
    ElMessage.error('获取地址列表失败')
    addressList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 每页条数改变
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  fetchAddressList()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  fetchAddressList()
}

// 删除地址
const handleDelete = async (id: number | undefined) => {
  if (!id) return
  try {
    await ElMessageBox.confirm('确定要删除该地址吗？', '提示', {
      type: 'warning'
    })
    await deleteAddress(id)
    ElMessage.success('删除成功')
    fetchAddressList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 设置默认地址
const handleSetDefault = async (id: number | undefined) => {
  if (!id) return
  try {
    await setDefaultAddress(id)
    ElMessage.success('设置成功')
    fetchAddressList()
  } catch (error) {
    ElMessage.error('设置失败')
  }
}

// 新增地址
const handleAdd = () => {
  formTitle.value = '新增地址'
  currentAddress.value = undefined
  formDialogVisible.value = true
}

// 编辑地址
const handleEdit = (address: AddressDTO) => {
  formTitle.value = '编辑地址'
  currentAddress.value = { ...address }
  formDialogVisible.value = true
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchAddressList()
}

// 获取地区名称
const getRegionNames = (address: AddressDTO) => {
  const province = getAreaName(address.province)
  const city = getAreaName(address.city)
  const town = getAreaName(address.town)
  return `${province}${city}${town}`
}

// 在 script setup 部分添加日期格式化函数
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  fetchAddressList()
})
</script>

<style scoped>
.address-container {
  padding: 20px;
  height: calc(100vh - 120px);
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: auto;
  padding: 20px 0;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
}

.address-detail-dialog {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.detail-item label {
  font-weight: bold;
  min-width: 80px;
}

.detail-item span {
  color: #666;
}
</style> 